import { KeyHandler, HotkeysEvent } from 'hotkeys-js'
import useHotKey from '@/hooks/useHotKey'
import { useEditorStore } from '@/stores/editor'

const wrapKeyHandler = (callback: KeyHandler) => {
  return (keyboardEvent: KeyboardEvent, hotkeysEvent: HotkeysEvent) => {
    console.log(hotkeysEvent.key)
    // 利用高阶函数阻止浏览器的默认行为
    keyboardEvent.preventDefault()
    callback(keyboardEvent, hotkeysEvent)
  }
}

export default function initHotKeys() {
  const store = useEditorStore()
  const currentId = computed(() => store.currentElementId)

  useHotKey('ctrl + c, command + c', () => {
    store.copyComponent(currentId.value)
  })

  useHotKey('ctrl + v, command + v', () => {
    store.pasteCopiedComponent()
  })

  useHotKey('backspace, delete', () => {
    store.deleteComponent(currentId.value)
  })

  useHotKey('esc', () => {
    store.setActive('')
  })

  useHotKey(
    'up',
    wrapKeyHandler(() => {
      store.moveComponent({ direction: 'Up', amount: 1, id: currentId.value })
    })
  )

  useHotKey(
    'down',
    wrapKeyHandler(() => {
      store.moveComponent({ direction: 'Down', amount: 1, id: currentId.value })
    })
  )

  useHotKey(
    'left',
    wrapKeyHandler(() => {
      store.moveComponent({ direction: 'Left', amount: 1, id: currentId.value })
    })
  )

  useHotKey(
    'right',
    wrapKeyHandler(() => {
      store.moveComponent({ direction: 'Right', amount: 1, id: currentId.value })
    })
  )

  useHotKey('shift + up', () => {
    store.moveComponent({ direction: 'Up', amount: 10, id: currentId.value })
  })

  useHotKey('shift + down', () => {
    store.moveComponent({ direction: 'Down', amount: 10, id: currentId.value })
  })

  useHotKey('shift + left', () => {
    store.moveComponent({ direction: 'Left', amount: 10, id: currentId.value })
  })

  useHotKey('shift + right', () => {
    store.moveComponent({ direction: 'Right', amount: 10, id: currentId.value })
  })

  useHotKey('ctrl + z, command + z', () => {
    store.undo()
  })

  useHotKey('ctrl + shift + z, command + shift + z', () => {
    store.redo()
  })
}
